package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import tech.aistar.entity.*;
import tech.aistar.service.*;
import tech.aistar.vo.Position;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/appointment")
public class AgentAppointmentController {
    @Autowired
    private IAppointmentTimeService appointmentTimeService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IConcernService concernService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private IEvaluateService evaluateService;
    @Autowired
    private IRegisterService registerService;
    @Autowired
    private IHouseService houseService;
    @RequestMapping("/agent")
    public @ResponseBody
    Result select(HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String appointment_date = null;
        if (request.getParameter("appointment_date") != "") {
            appointment_date = request.getParameter("appointment_date");
        }

        String time_quantum = request.getParameter("time_quantum");
        String agent_id = request.getParameter("agent_id");
        String tenant_id = request.getParameter("tenant_id");
        String house_id = request.getParameter("house_id");
        if (appointment_date == null) {
            return new Result("501", "日期不能为空");
        }

        Register register = (Register) request.getSession().getAttribute("register");
        if(register.getIdentity().equals("1")==false){
            return new Result("500","您不是租户,不可以预约经济人");
        }


//判断预约的人是否有时间

        List<AppointmentTime> appointmentTimes = appointmentTimeService.selectByTenantId(Integer.valueOf(tenant_id));
        for (AppointmentTime appointmentTime : appointmentTimes) {
            if (sdf.format(appointmentTime.getAppointmentDate()).equals(appointment_date) && appointmentTime.getAppointmentState().equals("预约成功") ) {
                if (appointmentTime.getTimeQuantum().equals(time_quantum)) {
                    return new Result("503", "预约失败,经纪人在此时间段没有时间");
                }
            }

        }


        try {
            List<AppointmentTime> appointmentTimes2 = appointmentTimeService.selectAgentByAppointmentDate(sdf.parse(appointment_date), Integer.valueOf(agent_id));
            for (AppointmentTime appointmentTime : appointmentTimes2) {
                if (sdf.format(appointmentTime.getAppointmentDate()).equals(appointment_date) && appointmentTime.getAppointmentState().equals("预约成功")) {
                    if (appointmentTime.getTimeQuantum().equals(time_quantum)) {

                        return new Result("504", "预约失败");
                    }
                }

            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        AppointmentTime appointmentTime = new AppointmentTime();
        appointmentTime.setAgentId(Integer.valueOf(agent_id));
        try {
            appointmentTime.setAppointmentDate(sdf.parse(appointment_date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        appointmentTime.setAppointmentState("审核中");
        appointmentTime.setHouseId(Integer.valueOf(house_id));
        appointmentTime.setTenantId(Integer.valueOf(tenant_id));
        appointmentTime.setTimeQuantum(time_quantum);
        appointmentTimeService.insert(appointmentTime);

        String tenant_name = tenantService.selectById(Integer.valueOf(tenant_id)).getName();
        Integer register_id = agentService.selectById(Integer.valueOf(agent_id)).getRegisterId();
        iMessageService.insertAll(new Message(register_id, "租户" + tenant_name + "预约了您,请到租户预约一栏进行确认", new Date()));
        return new Result("200", "正在预约,请等待经纪人同意");

    }

    @RequestMapping("/concern")
    public @ResponseBody
    Result select2(HttpServletRequest request) {
        String tenant_id = null;
        String house_id = null;
        if (request.getParameter("tenant_id") != "")
            tenant_id = request.getParameter("tenant_id");
        if (request.getParameter("house_id") != "")
            house_id = request.getParameter("house_id");
        Concern concern = concernService.selectById(Integer.valueOf(tenant_id), Integer.valueOf(house_id));
        if (concern == null) {
            return new Result("201", "没有收藏");
        }
        return new Result("200", "有收藏");
    }


    @RequestMapping("/changeconcern")
    public @ResponseBody
    Result select3(HttpServletRequest request) {
        String tenant_id = null;
        String house_id = null;
        if (request.getParameter("tenant_id") != "")
            tenant_id = request.getParameter("tenant_id");
        if (request.getParameter("house_id") != "")
            house_id = request.getParameter("house_id");
        Concern concern = concernService.selectById(Integer.valueOf(tenant_id), Integer.valueOf(house_id));
        if (concern == null) {
            concernService.insert(new Concern(Integer.valueOf(tenant_id), Integer.valueOf(house_id), new Date()));
            return new Result("202", "加入收藏");
        }
        concernService.deleteByDoubleId(Integer.valueOf(tenant_id), Integer.valueOf(house_id));
        return new Result("203", "取消收藏");
    }

    @RequestMapping("/changegrade1")
    public @ResponseBody
    Result select4(HttpServletRequest request) {
        Register register =(Register)  request.getSession().getAttribute("register");

        //做登陆判断是谁
        if(register==null){
            return new Result("501","请先登录");
        }
        String identity = register.getIdentity();
        if(!"1".equals(identity)){
            return new Result("502","抱歉,您不是租客");
        }
        return  new Result("200","您仅能查看");
    }
    @RequestMapping("/changegrade2")
    public @ResponseBody
    Result select5(HttpServletRequest request) {
        Register register =(Register)  request.getSession().getAttribute("register");
        String grade = null;
        Integer register_id=register.getId();
        String agent_id = null;
        if (request.getParameter("grade") != "")
            grade = request.getParameter("grade");
        if (request.getParameter("agent_id") != "")
            agent_id = request.getParameter("agent_id");
        if ("2".equals(registerService.selectById(register_id).getIdentity())) {
            if (Integer.valueOf(agent_id) == agentService.selectByregisterId(register_id).getId())
                return new Result("501", "请不要给自己打分");
        }
        if(evaluateService.findByregisterId(register_id,Integer.valueOf(agent_id))!=null){
            return  new Result("502","请不要重复打分");
        }else {
            evaluateService.insert(new Evaluate(Integer.valueOf(agent_id), Integer.valueOf(grade), register_id));
            return new Result("200", "打分成功");
        }

    }

    @RequestMapping("/pingfen1/{house_id}")
    public Integer detail1(@PathVariable("house_id") String house_id, HttpServletRequest request) {
        House house = houseService.selectById(Integer.valueOf(house_id));
        request.setAttribute("house", house);
        Integer agent_id=houseService.selectagentByhouseId(Integer.valueOf(house_id));
        List<Integer> evaluate_grads = evaluateService.findByagentId(Integer.valueOf(agent_id));
        int sum = 0;
        for (Integer evaluate_grad : evaluate_grads) {
            sum+=evaluate_grad;
        }
        Integer evaluate = sum/evaluate_grads.size();
        request.setAttribute("evaluate", evaluate);
        System.out.println(evaluate);
        return evaluate;
    }


    @RequestMapping("/dingwei")
    public  @ResponseBody
    Position detail6( Integer house_id, HttpServletRequest request) {
        House house = houseService.selectByhouseId(house_id);
        try {
            // 发起一个url网址的请求
            URL url = new URL("http://api.map.baidu.com/geocoder?address="+house.getResidentialQuarters()+"&output=json&key=zTAd0KdgeZxdb8P66ujClxjr01qZwzQR&city=苏州");
            URLConnection connection = url.openConnection();

            // 设置请求头
            connection.addRequestProperty("Accept", "application/json");

            // 获取网页的数据流
            InputStream input = connection.getInputStream();
            InputStreamReader reader = new InputStreamReader(input, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);

            // 解析并且获取InputStream中具体的数据，并且输出到控制台
            String line = "";
            String a="";
            String b="";

            while ((line = bufferedReader.readLine()) != null) {
                if(line.contains("lng"))
                    a= line.substring(line.indexOf(":")+1,line.indexOf(","));
                if(line.contains("lat"))
                    b= line.substring(line.indexOf(":")+1);
            }
            System.out.println(a);
            System.out.println(b);
            return new Position(a,b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Position("0","0");
    }

    }
